/*
 * @Description: 数据转换为api接口格式
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-04-18
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-04-20
 */

import { CmsQuestionTypeEnum } from '../enum/enum'
import type { ICmsQuestion } from '../type/type'

/**
 * 转换答案（解析工具格式->api接口格式）
 * @param questions 题目集
 * @returns 答案集
 */
export const convertApiAnswer = (questions: ICmsQuestion[]): SaveAnswerTypes.IAnswer[] => {
  return questions.map((question: ICmsQuestion) => {
    const { questionId, questionType } = question
    const result = {} as SaveAnswerTypes.IAnswer
    result.questionId = questionId
    if (questionType === CmsQuestionTypeEnum.INPUT) {
      result.value = {
        text: question.answer.input as string,
      }
    } else if (questionType === CmsQuestionTypeEnum.RADIO) {
      const checkedOption = question.options.find((item) => item.optionId === question.answer.radio)
      result.value = {
        choise: [{ value: checkedOption?.optionId, text: checkedOption?.optionText }],
      }
    } else if (questionType === CmsQuestionTypeEnum.CHECKBOX) {
      const choise: any = {}
      question.options.forEach((option) => {
        choise[option.optionId] = option.optionText
      })
      choise.value = question.answer.checkbox
      result.value = { choise }
    } else if (questionType === CmsQuestionTypeEnum.PICKER) {
      result.value = {
        choise: [question.answer.picker],
      }
    } else if (questionType === CmsQuestionTypeEnum.FILE) {
      result.value = {
        file: [question.answer.file],
      }
    }
    return result
  })
}
